package com.strongbj.iot.devices.newlight.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.entity.AlarmTagsPushReturnData;
import com.strongbj.iot.devices.newlight.message.NewLightMQMessage;
import com.strongbj.iot.devices.newlight.message.NewLightReaderMessage;
import com.strongbj.iot.devices.newlight.response.common.HandleTimeStamp;
import com.strongbj.iot.mq.producer.TopicSender;

import cn.hutool.core.date.DateUtil;
import io.netty.channel.ChannelHandlerContext;

/**
 * 0x3C，出错报警  
 * @author lei_w
 *
 */
public class ErrorResponseHandle implements IMessageHandle<NewLightReaderMessage, Object> {

	private static Logger logger = LogManager.getLogger(ChannelStateApplyResponseHandle.class.getName());
	
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	
	@Override
	public boolean isHandle(NewLightReaderMessage t) {
		if (Integer.valueOf("3C", 16).byteValue() == t.getType()) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightReaderMessage t) {
		String hostNumber = ByteUtil.bytesToAddress(t.getAddress()); // reader 地址码
		String timeStamp = ByteUtil.byteArrToHexString(t.getTime()); // 时间戳
		String errorCode = ByteUtil.byteArrToHexString(t.getBody()); //错误码
	
		String log = "\r\n===================================================" +
				"\r\n出错报警：" + 
				"\r\nREADER地址码：" + hostNumber + 
				"\r\n错误码：" + errorCode +
				"\r\n时间戳：" + HandleTimeStamp.handle(timeStamp);
		logger.info(log);
		NewLightMQMessage mes = new NewLightMQMessage();
		mes.setActioncode("alarmTagsPush");
		mes.setGUID(String.valueOf(DateUtil.date().getTime()));
		AlarmTagsPushReturnData atpr = new AlarmTagsPushReturnData();
		atpr.setReaderCode(hostNumber);
//		atpr.setType(2);
		mes.setPostdata(atpr);
		logger.info("=========alarmTagsPushReturn=======" + JSON.toJSONString(mes));
		topicSender.send("wh.reader."+hostNumber+".message", JSON.toJSONString(mes));
		return mes;
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
